import React from 'react';
import InputItem from 'antd-mobile/lib/input-item';
import List from 'antd-mobile/lib/list';
import Picker from 'antd-mobile/lib/picker';
import Toast from 'antd-mobile/lib/toast';
import BackNav from 'shared/components/BackNav';
import {
  fetchProvinceListApi,
  fetchCitylistListApi,
  fetchCountyListApi
} from 'shared/api';
import formatChars from 'shared/utils/formatChars';
import {
  fetchAddressInfoApi,
  addAddressApi,
  editAddressApi
} from '../api';
import './index.less';

export default class AddressForm extends React.PureComponent {
  state = {
    provinceList: [],
    citylistList: [],
    countyList: [],
    provinceValue: [],
    cityValue: [],
    countyValue: [],
    formData: {
      address: '',
      postcode: '',
      mobile: '',
      fullname: ''
    }
  }
  componentDidMount() {
    fetchProvinceListApi().then(({ data }) => {
      const provinceList = data.map((item) => ({ label: item.province, value: item.province_id }));
      this.setState({ provinceList });
    })
    const addressId = this.props.match.params.addressId;
    if (addressId) {
      fetchAddressInfoApi(({ address_id: addressId })).then(({ data }) => {
        this.updateForm(data)
      })
    }
  }

  updateForm(data) {
    const formData = {
      postcode: data.postcode,
      fullname: data.fullname,
      mobile: data.mobile,
      address: data.address
    }
    const { province_id, city_id, county_id } = data;
    this.setState({
      formData,
      provinceValue: [province_id]
    })
    this.handleProvinceChange([province_id]);
    this.handleCityChange([city_id]).then(() => {
      this.handleCountyChange([county_id])
    });
  }

  handleProvinceChange = (value) => {
    this.setState({ provinceValue: value });
    fetchCitylistListApi({ province_id: value[0] }).then(({ data }) => {
      const citylistList = data.map((item) => ({ label: item.city, value: item.city_id }));
      this.setState({ citylistList, countyValue: '' });
    })
  }

  handleCityChange = (value) => {
    this.setState({ cityValue: value });
    return fetchCountyListApi({ city_id: value[0] }).then(({ data }) => {
      const countyList = data.map((item) => ({ label: item.county, value: item.county_id }));
      this.setState({ countyList });
    })
  }

  handleCountyChange = (value) => {
    this.setState({ countyValue: value });
  }

  handleChange = (key, value) => {
    const formData ={...this.state.formData};
    formData[key] = value;
    this.setState({ formData });
  }

  handleBlur = (key, value) => {
    const formData ={...this.state.formData};
    formData[key] = value;
    this.setState({ formData });
  }

  getFormData(addressId) {
    const { formData, provinceValue, cityValue, countyValue } = this.state;
    const data = {
      ...formData,
      province_id: provinceValue[0],
      city_id: cityValue[0],
      county_id: countyValue[0]
    }
    if (addressId) {
      data.address_id = addressId;
    }
    return data;
  }

  hanldeSubmit = () => {
    const addressId = this.props.match.params.addressId;
    const mobileValue = this.getFormData().mobile;
    if (!mobileValue || mobileValue.length < 11) {
      Toast.info('手机号码必须为11位', 1)
      return;
    }
    Toast.info('加载中', 1)
    if (!addressId) {
      addAddressApi(this.getFormData()).then((result) => {
        if (result.code === 1000) {
          __self.history.goBack();
        } else {
          Toast.info('保存失败参数错误', 1)
        }
      })
    } else {
      editAddressApi(this.getFormData(addressId)).then((result) => {
        if (result.code === 1000) {
          __self.history.push('/account/addressManage')
        } else {
          Toast.info('保存失败参数错误', 1)
        }
      })
    }
  }

  render() {
    const { provinceList, citylistList, countyList,
      provinceValue, cityValue, countyValue, formData } = this.state;
    const addressId = this.props.match.params.addressId;
    return ([
      <BackNav key="backnav" title={`${addressId ? '编辑': '新增'}收货人信息`} />,
      (
        <div className="address-form" key="address-form">
          <div className="address-form-title">
            <span>收货人信息</span>
          </div>
          <div className="address-form-container">
            <List className='form-item'>
              <div className="am-list-item am-input-item am-list-item-middle area-select">
                <div className="am-list-line">
                  <div className="am-input-label am-input-label-5">
                    <span>所在地区<sup>*</sup></span>
                  </div>
                  <div className="am-input-control">
                    <Picker
                      data={provinceList}
                      cols={1}
                      className="forss"
                      value={provinceValue}
                      onChange={this.handleProvinceChange}
                    >
                      <List.Item arrow="horizontal" />
                    </Picker>
                    <Picker
                      data={citylistList}
                      cols={1}
                      className="forss"
                      value={cityValue}
                      onChange={this.handleCityChange}
                    >
                      <List.Item arrow="horizontal" />
                    </Picker>
                    <Picker
                      data={countyList}
                      cols={1}
                      className="forss"
                      value={countyValue}
                      onChange={this.handleCountyChange}
                    >
                      <List.Item arrow="horizontal" />
                    </Picker>
                  </div>
                </div>
              </div>
              <InputItem
                value={formData.address}
                onChange={(value) => {
                  this.handleChange('address', value)
                }}

                onBlur={(value) => { this.handleBlur('address', formatChars(value)) }}
              >
                <span>详细地址<sup>*</sup></span>
              </InputItem>
              <InputItem
                value={formData.postcode}
                type="number"
                onChange={(value) => {
                  this.handleChange('postcode', value)
                }}
              >
                <span>邮政编码</span>
              </InputItem>
              <InputItem
                value={formData.fullname}
                placeholder="长度不超过25个字符"
                onChange={(value) => {
                  this.handleChange('fullname', value)
                }}
                onBlur={(value) => { this.handleBlur('fullname', formatChars(value)) }}
              >
                <span>收货人姓名<sup>*</sup></span>
              </InputItem>
              <InputItem
                value={formData.mobile}
                type="number"
                maxLength={11}
                onChange={(value) =>{ this.handleChange('mobile', value) }}
              >
                <span>手机号码<sup>*</sup></span>
              </InputItem>
            </List>
            <div className="address-submit">
              <span className="button" onClick={this.hanldeSubmit}>保存收货信息</span>
            </div>
          </div>
        </div>
      )
    ]
    )
  }
}
